package com.hy.frame.mvvm.base

import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding


abstract class BaseActivity<DB : ViewDataBinding, VM : BaseViewModel> : com.hy.frame.base.BaseActivity() {
    protected var mBinding: DB? = null
    protected var mModel: VM? = null

    override fun initLayout() {
        initDataBinding()
        initViewModel()
        initObserver()
    }

    private fun initDataBinding() {
        if (layoutId != 0) {
            mBinding = DataBindingUtil.setContentView(this, layoutId)
            mBinding!!.lifecycleOwner = this
        }
    }

    private fun initViewModel() {
        if (viewModel != null) {
            mModel = defaultViewModelProviderFactory.create(viewModel!!)
            if (variableId != 0) {
                mBinding?.setVariable(variableId, mModel)
            }
        }
    }

    protected open fun initObserver() {
        mModel?.loadingUI?.observe(this, {
            if (it.display) {
                showLoading(it.msg)
            } else {
                dismissLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        mBinding?.unbind()
        mBinding = null
        mModel = null
    }

    protected open val layoutId: Int = 0

    protected open val variableId: Int = 0

    protected open val viewModel: Class<VM>? = null

    abstract fun showLoading(msg: String? = null)

    abstract fun dismissLoading()

    abstract fun showToast(msg: String? = null)
}